package cn.edu.ctbu.dp07.controller;

import cn.edu.ctbu.dp07.entity.Course;
import cn.edu.ctbu.dp07.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 显示课程列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Course> courses = courseService.findAll();
        model.addAttribute("courses", courses);
        return "course/list";
    }

    /**
     * 显示添加课程页面
     */
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("course", new Course());
        return "course/edit";
    }

    /**
     * 显示编辑课程页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        Course course = courseService.findById(id);
        model.addAttribute("course", course);
        return "course/edit";
    }

    /**
     * 保存课程信息
     */
    @PostMapping("/save")
    public String save(Course course) {
        courseService.save(course);
        return "redirect:/course/list";
    }

    /**
     * 删除课程
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        courseService.deleteById(id);
        return "redirect:/course/list";
    }
    
    /**
     * 根据课程名称或编号查询课程
     */
    @GetMapping("/search")
    public String search(@RequestParam(required = false) String keyword, Model model) {
        List<Course> courses;
        if (keyword != null && !keyword.isEmpty()) {
            courses = (List<Course>) courseService.findByCourseNameContaining(keyword);
        } else {
            courses = courseService.findAll();
        }
        model.addAttribute("courses", courses);
        model.addAttribute("keyword", keyword);
        return "course/list";
    }
} 